package com.xmut.bs.handaccount.activity;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.helper.ItemTouchHelper;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;

import com.xmut.bs.handaccount.GlideApp;
import com.xmut.bs.handaccount.R;
import com.xmut.bs.handaccount.base.ToolbarBaseActivity;
import com.xmut.bs.handaccount.bmob.Article;
import com.xmut.bs.handaccount.bmob.Collection;
import com.xmut.bs.handaccount.util.CommonUtil;
import com.xmut.bs.handaccount.util.DisplayUtils;
import com.xmut.bs.handaccount.util.DividerItemDecoration;
import com.xmut.bs.handaccount.util.GlideCircleTransform;
import com.xmut.bs.handaccount.util.ImageUtils;
import com.xmut.bs.handaccount.util.SDCardUtil;
import com.xmut.bs.handaccount.util.StringUtil;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import java.io.File;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.datatype.BmobFile;
import cn.bmob.v3.datatype.BmobPointer;
import cn.bmob.v3.datatype.BmobRelation;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.SaveListener;
import cn.bmob.v3.listener.UpdateListener;
import cn.bmob.v3.listener.UploadFileListener;
import rx.Observable;
import rx.Observer;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

import static com.xmut.bs.handaccount.base.Constants.PARAM_ARTICLE;
import static com.xmut.bs.handaccount.base.Constants.PARAM_ARTICLE_ID;
import static com.xmut.bs.handaccount.base.Constants.PARAM_EDIT;

/**
 * Description
 * Created by Dollkey on 2018/4/22.
 */

public class AddCollectionActivity extends ToolbarBaseActivity {
    @BindView(R.id.add_pic)
    ImageView mAddPic;
    @BindView(R.id.title)
    EditText mTitle;
    @BindView(R.id.recycle_view)
    RecyclerView mRecycleView;

    private ProgressDialog insertDialog;
    private ProgressDialog saveDialog;
    private Collection mCollection;
    private String mImgUrl;
    private CommonAdapter<Article> mAdapter;
    private List<Article> mList;

    @Override
    protected String getSubTitle() {
        return "合辑管理";
    }

    @Override
    protected int bindLayoutId() {
        return R.layout.activity_add_collection;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        insertDialog = new ProgressDialog(this);
        insertDialog.setMessage("正在插入图片...");
        saveDialog = new ProgressDialog(this);
        saveDialog.setMessage("正在保存...");
        mList = new ArrayList<>();
        mRecycleView.setItemAnimator(new DefaultItemAnimator());
        mRecycleView.setLayoutManager(new LinearLayoutManager(mContext));
        mRecycleView.addItemDecoration(new DividerItemDecoration(mContext,
                DisplayUtils.dp2px(mContext, 8),
                getResources().getColor(R.color.grey100)).setHasLeftOrRight(false).setHasTopAndBottom(false));
        ItemTouchHelper itemTouchHelper = new ItemTouchHelper(new ItemTouchHelper.Callback() {

            @Override
            public boolean isLongPressDragEnabled() {
                return false;
            }

            @Override
            public boolean isItemViewSwipeEnabled() {
                return true;
            }

            @Override
            public int getMovementFlags(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
                return makeMovementFlags(0, ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT);
            }

            @Override
            public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
                return false;
            }

            @Override
            public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
                final Article article = mList.get(viewHolder.getAdapterPosition());
                BmobRelation relation = new BmobRelation();
                article.setTableName("Article");
                relation.remove(article);
                mCollection.setTableName("Collection");
                mCollection.setArticle(relation);
                mCollection.update(new UpdateListener() {
                    @Override
                    public void done(BmobException e) {
                        if (e == null) {
                            showToast("删除成功");
                            mList.remove(article);
                            mAdapter.notifyDataSetChanged();
                        } else {
                            showToast("失败：" + e.getMessage() + "," + e.getErrorCode());
                            mAdapter.notifyDataSetChanged();
                        }
                    }
                });
            }
        });
        itemTouchHelper.attachToRecyclerView(mRecycleView);
        mAdapter = new CommonAdapter<Article>(mContext, R.layout.item_article, mList) {
            @Override
            protected void convert(ViewHolder holder, final Article article, int position) {
                holder.getConvertView().setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        startActivity(new Intent().putExtra(PARAM_ARTICLE_ID, article), ArticleDetailActivity.class);
                    }
                });
                holder.setText(R.id.goods_name, article.getTitle());
                holder.setText(R.id.username, article.getUser().getNickName());
                holder.setVisible(R.id.start_video_img, article.getContainVideo());
                ImageView closeImg = holder.getView(R.id.image_close);
                closeImg.setVisibility(View.VISIBLE);
                closeImg.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        BmobRelation relation = new BmobRelation();
                        article.setTableName("Article");
                        relation.remove(article);
                        mCollection.setArticle(relation);
                        mCollection.setTableName("Collection");
                        mCollection.update(new UpdateListener() {
                            @Override
                            public void done(BmobException e) {
                                if (e == null) {
                                    showToast("删除成功");
                                    mList.remove(article);
                                    mAdapter.notifyDataSetChanged();
                                } else {
                                    showToast("失败：" + e.getMessage() + "," + e.getErrorCode());
                                }
                            }
                        });
                    }
                });
                ImageView coverImg = holder.getView(R.id.cover_img);
                ImageView avatarImg = holder.getView(R.id.avatar_img);
                GlideApp.with(coverImg).load(article.getCoverImg()).override(1200, 600).centerCrop().into(coverImg);
                GlideApp.with(coverImg).load(article.getUser().getAvatar())
                        .placeholder(R.mipmap.ic_head_img).error(R.mipmap.ic_head_img)
                        .transform(new GlideCircleTransform(mContext)).override(60, 60).into(avatarImg);
            }
        };
        mRecycleView.setAdapter(mAdapter);
        if (mCollection != null) {
            GlideApp.with(mAddPic).load(mCollection.getImgUrl()).placeholder(R.color.grey300).error(R.color.grey300).centerCrop().into(mAddPic);
            mTitle.setText(mCollection.getName());
            query();
        }
    }

    private void query() {
        BmobQuery<Article> query = new BmobQuery<>();
        query.addWhereRelatedTo("article", new BmobPointer(mCollection));
        query.include("user");
        query.findObjects(new FindListener<Article>() {
            @Override
            public void done(List<Article> list, BmobException e) {
                if (e == null) {
                    mList.clear();
                    mList.addAll(list);
                    mAdapter.notifyDataSetChanged();
                } else {
                    Log.i("bmob", "失败：" + e.getMessage());
                }
            }
        });
    }

    @OnClick(R.id.add_pic)
    public void onViewClicked() {
        callGallery();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_delete, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_add:
                if (mCollection == null) {
                    showToast("请先创建合辑");
                    return super.onOptionsItemSelected(item);
                }
                startActivityForResult(ArticleSelectActivity.class, new Intent().putExtra(PARAM_EDIT, mCollection)
                        .putExtra(PARAM_ARTICLE, (Serializable) mList), 2);
                break;
            case R.id.action_save:
                if (mCollection == null)
                    save();
                else {
                    update();
                }
                break;
            case R.id.action_delete:
                if (mCollection == null) {
                    showToast("请先创建合辑");
                    return super.onOptionsItemSelected(item);
                }
                mCollection.delete(new UpdateListener() {
                    @Override
                    public void done(BmobException e) {
                        if (e == null) {
                            showToast("删除成功");
                            onBackPressed();
                        } else {
                            showToast("失败：" + e.getMessage() + "," + e.getErrorCode());
                        }
                    }
                });
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    private void update() {
        saveDialog.show();
        if (StringUtil.isNull(mImgUrl)) {
            mCollection.setName(mTitle.getText().toString().trim());
            mCollection.update(new UpdateListener() {
                @Override
                public void done(BmobException e) {
                    saveDialog.dismiss();
                    if (e == null) {
                        showToast("保存成功");
                    } else {
                        showToast("失败：" + e.getMessage() + "," + e.getErrorCode());
                    }
                }
            });
        } else {
            final BmobFile bmobFile = new BmobFile(new File(mImgUrl));
            bmobFile.uploadblock(new UploadFileListener() {

                @Override
                public void done(BmobException e) {
                    if (e == null) {
                        mCollection.setName(mTitle.getText().toString().trim());
                        mCollection.setImgUrl(bmobFile.getFileUrl());
                        mCollection.update(new UpdateListener() {
                            @Override
                            public void done(BmobException e) {
                                saveDialog.dismiss();
                                if (e == null) {
                                    showToast("保存成功");
                                } else {
                                    showToast("失败：" + e.getMessage() + "," + e.getErrorCode());
                                }
                            }
                        });
                    } else {
                        saveDialog.dismiss();
                        showToast("上传文件失败：" + e.getMessage());
                    }

                }

                @Override
                public void onProgress(Integer value) {
                }
            });
        }
    }

    private void save() {
        if (StringUtil.isNull(mImgUrl)) {
            showToast("请选择图片");
            return;
        }
        saveDialog.show();
        final BmobFile bmobFile = new BmobFile(new File(mImgUrl));
        bmobFile.uploadblock(new UploadFileListener() {
            @Override
            public void done(BmobException e) {
                if (e == null) {
                    final Collection collection = new Collection(bmobFile.getFileUrl(), mTitle.getText().toString().trim());
                    collection.save(new SaveListener<String>() {
                        @Override
                        public void done(String s, BmobException e) {
                            saveDialog.dismiss();
                            if (e == null) {
                                mCollection = collection;
                                showToast("保存成功");
                            } else {
                                showToast("失败：" + e.getMessage() + "," + e.getErrorCode());
                            }
                        }
                    });
                } else {
                    saveDialog.dismiss();
                    showToast("上传文件失败：" + e.getMessage());
                }

            }

            @Override
            public void onProgress(Integer value) {
            }
        });
    }

    @Override
    public void onBackPressed() {
        setResult(Activity.RESULT_OK);
        finish();
    }

    @Override
    protected void initParams(Intent intent) {
        mCollection = (Collection) intent.getSerializableExtra(PARAM_EDIT);
    }

    /**
     * 调用图库选择
     */
    private void callGallery() {
        //调用系统图库
        Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");// 相片类型
        startActivityForResult(intent, 1);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, final Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (data != null) {
                if (requestCode == 1) {
                    //处理调用系统图库
                    insertImagesSync(data);
                }
            }
            if (requestCode == 2) {
                query();
            }
        }
    }

    /**
     * 异步方式插入图片
     */
    private void insertImagesSync(final Intent data) {
        insertDialog.show();
        Observable
                .create(new Observable.OnSubscribe<String>() {
                    @Override
                    public void call(Subscriber<? super String> subscriber) {
                        try {
                            int width = CommonUtil.getScreenWidth(mContext);
                            int height = CommonUtil.getScreenHeight(mContext);
                            Uri uri = data.getData();
                            Bitmap bitmap;
                            ContentResolver cr = mContext.getContentResolver();
                            Cursor cursor = cr.query(uri, null, null, null, null);
                            cursor.moveToFirst();
                            String img_path = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA));
                            bitmap = ImageUtils.getSmallBitmap(img_path, width, height);//压缩图片
                            cursor.close();
                            subscriber.onNext(SDCardUtil.saveToSdCard(bitmap));
                            subscriber.onCompleted();
                        } catch (Exception e) {
                            e.printStackTrace();
                            subscriber.onError(e);
                        }
                    }
                })
                .onBackpressureBuffer()
                .subscribeOn(Schedulers.io())//生产事件在io
                .observeOn(AndroidSchedulers.mainThread())//消费事件在UI线程
                .subscribe(new Observer<String>() {
                    @Override
                    public void onCompleted() {
                        insertDialog.dismiss();
                    }

                    @Override
                    public void onError(Throwable e) {
                        insertDialog.dismiss();
                        showToast("图片添加失败" + e.getMessage());
                    }

                    @Override
                    public void onNext(String imagePath) {
                        mImgUrl = imagePath;
                        GlideApp.with(mAddPic).load(imagePath).placeholder(R.color.grey300).error(R.color.grey300).centerCrop().into(mAddPic);
                    }
                });
    }
}
